import data from './data.js';

document.addEventListener('DOMContentLoaded', () => {
    const dataTable = document.getElementById('dataTable');
    const analysisResults = document.getElementById('analysisResults');

    // 填充数据表格
    fillDataTable(dataTable, data);

    // 进行数据分析并显示结果
    analyzeData(data, analysisResults);
});

function fillDataTable(table, data) {
    const tbody = table.querySelector('tbody');
    tbody.innerHTML = '';

    for (let key in data) {
        if (key !== 'years') {
            const row = document.createElement('tr');
            row.innerHTML = `<td>${key}</td>`;
            data[key].forEach(value => {
                const cell = document.createElement('td');
                cell.textContent = value;
                row.appendChild(cell);
            });
            tbody.appendChild(row);
        }
    }
}

function analyzeData(data, resultsDiv) {
    const analysisResults = [];

    for (let key in data) {
        if (key !== 'years') {
            const values = data[key];
            const avg = calculateAverage(values);
            const max = Math.max(...values);
            const min = Math.min(...values);

            analysisResults.push({
                indicator: key,
                average: avg.toFixed(2),
                max: max,
                min: min
            });
        }
    }

    resultsDiv.innerHTML = '<h2>数据分析结果</h2>';
    analysisResults.forEach(result => {
        resultsDiv.innerHTML += `
            <p><strong>${result.indicator}:</strong> 平均值: ${result.average}, 最大值: ${result.max}, 最小值: ${result.min}</p>
        `;
    });
}

function calculateAverage(values) {
    return values.reduce((sum, value) => sum + value, 0) / values.length;
}